package com.itany.cms.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.cms.constant.DictConstant;
import com.itany.cms.constant.StatusConstant;
import com.itany.cms.dao.ChapterMapper;
import com.itany.cms.dao.CourseMapper;
import com.itany.cms.dao.CourseTypeMapper;
import com.itany.cms.entity.Chapter;
import com.itany.cms.entity.Course;
import com.itany.cms.entity.CourseType;
import com.itany.cms.entity.Resource;
import com.itany.cms.exception.CourseExistException;
import com.itany.cms.exception.FileUploadErrorException;
import com.itany.cms.exception.RequestParameterErrorException;
import com.itany.cms.service.CourseService;
import com.itany.cms.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CourseServiceImpl implements CourseService {
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    CourseTypeMapper typeMapper;
    @Autowired
    ChapterMapper chapterMapper;

    @Override
    public PageInfo<Course> findByParams(Course courseParam, String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.COURSE_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.COURSE_DEFAULT_PAGE_SIZE;
        }
        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        if (!ParameterUtil.isNull(courseParam.getAuthor())) {
            wrapper.like("author", courseParam.getAuthor());
        }
        if (!ParameterUtil.isNull(courseParam.getCourseName())) {
            wrapper.like("course_name", courseParam.getCourseName());
        }
        if (!ParameterUtil.isNull(courseParam.getStatus())) {
            wrapper.eq("status", courseParam.getStatus());
        }
        if (!ParameterUtil.isNull(courseParam.getCourseTypeId())) {
            wrapper.eq("course_type_id", courseParam.getCourseTypeId());
        }if (!ParameterUtil.isNull(courseParam.getEndDate())||!ParameterUtil.isNull(courseParam.getEndDate())) {
            wrapper.between("create_date", courseParam.getStartDate(), courseParam.getEndDate());
        }
        List<Course> courses = courseMapper.selectList(wrapper);
        for (Course course:courses) {
            QueryWrapper<CourseType> wrapper1 = new QueryWrapper();
            wrapper1.eq("id",course.getCourseTypeId());
            List<CourseType> types = typeMapper.selectList(wrapper1);
            course.setCourseTypeName(types.get(0).getTypeName());
        }
        PageInfo<Course> coursePage = new PageInfo<>(courses);
        return coursePage;
    }

    @Override
    public PageInfo<Chapter> findChapter(Chapter chapterParam, String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.RESOURCE_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.RESOURCE_DEFAULT_PAGE_SIZE;
        }
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        QueryWrapper<Chapter> wrapper =new QueryWrapper<>();
        wrapper.eq("course_id",chapterParam.getId());
        List<Chapter> chapters = chapterMapper.selectList(wrapper);
        PageInfo<Chapter> chapterPageInfo = new PageInfo<>(chapters);
        return chapterPageInfo;
    }

    @Override
    public void modifyStatus(String id, String status) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id) || ParameterUtil.isNull(status)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        Course course = new Course();
        course.setId(Integer.parseInt(id));
        course.setStatus(Integer.parseInt(status));
        if (course.getStatus() == StatusConstant.COURSE_STATUS_ENABLED) {
            course.setStatus(StatusConstant.COURSE_STATUS_DISABLED);
        } else {
            course.setStatus(StatusConstant.COURSE_STATUS_ENABLED);
        }
        courseMapper.updateById(course);
    }

    @Override
    public void addCourse(String courseName,String courseInfo, String author, MultipartFile file, String recommendationGrade, String courseTypeId) throws RequestParameterErrorException, CourseExistException, FileUploadErrorException {
        if (ParameterUtil.isNull(courseName) || ParameterUtil.isNull(author) || ParameterUtil.isNull(recommendationGrade) || file.isEmpty() || ParameterUtil.isNull(courseTypeId)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        QueryWrapper<Course> wrapper = new QueryWrapper();
        wrapper.eq("course_name", courseName)
                .eq("course_type_id", courseTypeId);
        List<Course> courses = courseMapper.selectList(wrapper);
        if (!courses.isEmpty()) {
            throw new CourseExistException("该类型的商品已经存在");
        }

        Course course = new Course();
        course.setCourseName(courseName);
        course.setAuthor(author);
        course.setRecommendationGrade(Integer.parseInt(recommendationGrade));
        course.setCourseTypeId(Integer.parseInt(courseTypeId));
        course.setCourseInfo(courseInfo);
        course.setStatus(StatusConstant.COURSE_STATUS_ENABLED);
        CourseType courseType = typeMapper.selectById(Integer.parseInt(courseTypeId));
        try { // 上传商品图片
            // 指定相对路径
            String path = DictConstant.COURSE_IMAGE_ROOT_FOLDER + new SimpleDateFormat("yyyyMMdd").format(new Date());
            // 获取绝对路径
//        String cp = session.getServletContext().getRealPath(path);
            String cp = ResourceUtils.getURL("classpath:").getPath() + path;
            System.out.println("***************当前课程图片的路径为:" + cp);
            // 创建目录
            File f = new File(cp);
            f.mkdirs();

            // 生成商品图片属性值
            course.setCoverImageUrl(path + "/" + file.getOriginalFilename());
            // 添加商品
            courseMapper.insert(course);
            // 上传图片
            file.transferTo(new File(cp, file.getOriginalFilename()));
        } catch (IOException e) {
            throw new FileUploadErrorException("课程图片上传失败");
        }
    }

    @Override
    public void modifyCourse(String id, String name, String author, MultipartFile file, String recommendationGrade, String courseTypeId) throws RequestParameterErrorException, CourseExistException, FileUploadErrorException {
        if (ParameterUtil.isNull(id) || ParameterUtil.isNull(name) || ParameterUtil.isNull(author) || ParameterUtil.isNull(recommendationGrade) || ParameterUtil.isNull(courseTypeId)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        // 同一种类型的商品名不能重复
        QueryWrapper<Course> wrapper = new QueryWrapper();
        wrapper.eq("course_name", name)
                .eq("course_type_id", courseTypeId)
                .ne("id", id);
        List<Course> courses = courseMapper.selectList(wrapper);
        if (!courses.isEmpty()) {
            throw new CourseExistException("该类型的商品已经存在");
        }

        Course course = new Course();
        course.setId(Integer.parseInt(id));
        course.setCourseName(name);
        course.setAuthor(author);
        course.setRecommendationGrade(Integer.parseInt(recommendationGrade));
        course.setCourseTypeId(Integer.parseInt(courseTypeId));

        // 判断是否修改商品图片
        if (file.isEmpty()) {
            // 不需要重新上传图片,直接修改
            courseMapper.updateById(course);
        } else {

            try {
                // 先删除原来的商品图片
                // 获取原来的商品图片地址
                Course p = (Course) courseMapper.selectById(id);
                String image = p.getCoverImageUrl();
                // 获取绝对路径
//            String cp = session.getServletContext().getRealPath(image);
                String cp = ResourceUtils.getURL("classpath:").getPath() + image;
                File f = new File(cp);
                f.delete();

                // 再上传新的商品图片
                String path = DictConstant.COURSE_IMAGE_ROOT_FOLDER + new SimpleDateFormat("yyyyMMdd").format(new Date());
                // 获取绝对路径
                cp = ResourceUtils.getURL("classpath:").getPath() + path;
                // 创建目录
                File f2 = new File(cp);
                f2.mkdirs();

                // 生成商品图片属性值
                course.setCoverImageUrl(path + "/" + file.getOriginalFilename());
                // 修改商品信息
                courseMapper.updateById(course);
                // 上传图片
                file.transferTo(new File(cp, file.getOriginalFilename()));
            } catch (IOException e) {
                throw new FileUploadErrorException("课程图片上传失败");
            }
        }
    }

}
